package com.projx.accounting.controller;

import com.projx.accounting.module.User;
import com.projx.accounting.service.AuthService;
import com.projx.accounting.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserService svc;
    private final AuthService auth;

    public UserController(UserService svc, AuthService auth) {
        this.svc = svc;
        this.auth = auth;
    }

    @PostMapping
    public ResponseEntity<User> create(@RequestBody User user) {
        User created = svc.create(user);
        return ResponseEntity.created(URI.create("/api/users/" + created.getId())).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> get(@PathVariable String id) {
        return svc.findById(id).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 不公开列出所有用户（安全）

    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable String id, @RequestBody User user) {
        if (user.getId() == null) user.setId(id);
        if (!id.equals(user.getId())) {
            return ResponseEntity.badRequest().build();
        }
        User updated = svc.update(user);
        return ResponseEntity.ok(updated);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable String id) {
        boolean removed = svc.delete(id);
        return removed ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
        return svc.authenticate(username, password)
                .map(user -> {
                    String token = auth.createTokenForUser(user.getId());
                    // 返回 JSON 包含 token 和 username
                    return ResponseEntity.ok(new java.util.HashMap<String, String>() {{
                        put("token", token);
                        put("username", user.getUsername());
                    }});
                }).orElseGet(() -> ResponseEntity.status(401).build());
    }
}
